/*
 *    Copyright (c) 2018-2025, cloud All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: cloud
 */

package com.fuyao.cloud.asset.warehous.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fuyao.cloud.asset.constant.WarehousConstant;
import com.fuyao.cloud.asset.dto.warehous.WarehousSearchDTO;
import com.fuyao.cloud.asset.enums.AssetStatusEnum;
import com.fuyao.cloud.common.core.constant.CommonConstants;
import com.fuyao.cloud.common.core.controller.FlowableController;
import com.fuyao.cloud.common.core.flowable.enums.ProcessStatusEnum;
import com.fuyao.cloud.common.core.util.R;
import com.fuyao.cloud.common.data.mybatis.SpliceQueryWrapper;
import com.fuyao.cloud.common.log.annotation.SysLog;
import com.fuyao.cloud.asset.entity.warehous.Warehous;
import com.fuyao.cloud.asset.warehous.service.WarehousService;
import org.springframework.security.access.prepost.PreAuthorize;
import com.fuyao.cloud.common.excel.annotation.ResponseExcel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.server.PathParam;
import java.util.List;
import java.util.Map;

/**
 * 入库管理
 *
 * @author liyue
 * @date 2021-12-06 20:19:22
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/warehous")
@Api(value = "warehous", tags = "入库管理管理")
public class WarehousController implements FlowableController {

    private final WarehousService warehousService;

    /**
     * 分页查询
     *
     * @param page      分页对象
     * @param searchDTO 入库管理
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('warehous_warehous_view')")
    public R page(Page page, WarehousSearchDTO searchDTO) {
        return R.ok(warehousService.page(page, SpliceQueryWrapper.spliceSearchCondition(searchDTO), searchDTO));
    }

    @ApiOperation(value = "入库单分页查询", notes = "分页查询")
    @PostMapping("/getWarehousPage")
    @PreAuthorize("@pms.hasPermission('warehous_warehous_view')")
    public R getWarehousPage(Page page, WarehousSearchDTO searchDTO) {
        return R.ok(warehousService.getWarehousPage(page, SpliceQueryWrapper.spliceSearchCondition(searchDTO), searchDTO));
    }

    /**
     * 通过id查询入库管理
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('warehous_warehous_view')")
    public R getById(@PathVariable("id") Long id) {
        return R.ok(warehousService.getById(id));
    }

    /**
     * 新增入库管理
     *
     * @param warehous 入库管理
     * @return R
     */
    @ApiOperation(value = "新增入库管理", notes = "新增入库管理")
    @SysLog("新增入库管理")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('warehous_warehous_add')")
    public R save(@RequestBody Warehous warehous) {
        warehousService.save(warehous);
        return R.ok(warehous);
    }

    /**
     * 修改入库管理
     *
     * @param warehous 入库管理
     * @return R
     */
    @ApiOperation(value = "修改入库管理", notes = "修改入库管理")
    @SysLog("修改入库管理")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('warehous_warehous_edit')")
    public R updateById(@RequestBody Warehous warehous) {
        return R.ok(warehousService.updateById(warehous));
    }

    /**
     * 通过id删除入库管理
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除入库管理", notes = "通过id删除入库管理")
    @SysLog("通过id删除入库管理")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('warehous_warehous_del')")
    public R removeById(@PathVariable Long id) {
        return R.ok(warehousService.removeById(id));
    }


    /**
     * 导出excel 表格
     *
     * @param searchDTO 查询条件
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('warehous_warehous_export')")
    public List export(WarehousSearchDTO searchDTO, String classify) {
        return warehousService.listWarehous(SpliceQueryWrapper.spliceSearchCondition(searchDTO), classify);
    }

    /**
     * 入库单创建方法
     *
     * @return 入库单创建对象
     */
    @GetMapping("/create")
    @PreAuthorize("@pms.hasPermission('warehous_warehous_add')")
    public R create(@PathParam("classify") String classify) {
        return R.ok(this.warehousService.create(classify));
    }

    /**
     * 入库单编辑方法
     *
     * @return 入库单创建对象
     */
    @GetMapping("/edit/{id}")
    @PreAuthorize("@pms.hasPermission('warehous_warehous_edit')")
    public R edit(@PathVariable("id") Long id) {
        return R.ok(this.warehousService.edit(id));
    }

    @ApiOperation(value = "批量删除入库管理", notes = "批量删除入库管理")
    @SysLog("批量删除入库管理" )
    @DeleteMapping("/batchDelete" )
    @PreAuthorize("@pms.hasPermission('warehous_warehous_del')" )
    public R batchDelete(@RequestBody List<Long> ids) {
        return warehousService.batchDelete(ids);
    }

    @ApiOperation(value = "起草环节结束回调方法", notes = "起草环节结束回调方法")
    @PostMapping(value = "/draftEndCallback", produces = "application/json")
    @Override
    public R draftEndCallback(HttpServletRequest request, @RequestBody Map<String, Object> params) {
        if (params.containsKey("businessKey")) {
            String id = CollUtil.getLast(StrUtil.split(params.get("businessKey") + "", ":"));
            Warehous warehous = this.warehousService.getById(id);
            Assert.isTrue(ObjectUtils.isNotEmpty(warehous), String.format("未找到对应的业务数据：%s", id));
            warehous.setStatus(AssetStatusEnum.PROCESSING.getCode());
            this.warehousService.updateById(warehous);
            return R.ok(warehous,"修改状态成功");
        }
        return R.ok(CommonConstants.SUCCESS,"起草环节结束回调方法");
    }

    @ApiOperation(value = "回退至起草环节回调方法", notes = "回退至起草环节回调方法")
    @PostMapping(value = "/returnCallback", produces = "application/json")
    @Override
    public R returnCallback(HttpServletRequest request, @RequestBody Map<String, Object> params) {
        if (params.containsKey("businessKey")) {
            String id = CollUtil.getLast(StrUtil.split(params.get("businessKey") + "", ":"));
            Warehous warehous = this.warehousService.getById(id);
            Assert.isTrue(ObjectUtils.isNotEmpty(warehous), String.format("未找到对应的业务数据：%s", id));
            warehous.setStatus(AssetStatusEnum.DRAFT.getCode());
            this.warehousService.updateById(warehous);
            return R.ok(warehous,"修改状态成功");
        }
        return R.ok(CommonConstants.SUCCESS,"回退至起草环节回调方法");
    }

    @ApiOperation(value = "流程结束回调方法", notes = "流程结束回调方法")
    @PostMapping(value = "/callback", produces = "application/json")
    @Override
    public R finishEndCallback(HttpServletRequest request, @RequestBody Map<String, Object> params) {
        if (params.containsKey("businessKey")) {
            String id = CollUtil.getLast(StrUtil.split(params.get("businessKey") + "", ":"));
            Warehous warehous = this.warehousService.getById(id);
            Assert.isTrue(ObjectUtils.isNotEmpty(warehous), String.format("未找到对应的业务数据：%s", id));
            String status = params.containsKey(ProcessStatusEnum.ZZ.toString()) ? AssetStatusEnum.INVALID.getCode() : AssetStatusEnum.FINISH.getCode();
            warehous.setStatus(status);
            this.warehousService.updateById(warehous);
            // 冲销
            if(WarehousConstant.WAREHOUS_CLASSIFY_1.equals(warehous.getClassify())){
                this.warehousService.classifyAssetCard(warehous);
            }
            return R.ok(warehous, "修改状态成功");
        }
        return R.failed("未找到对应的业务数据");
    }

}
